import axios from "axios";
import router from "../router";
import Cookies from "js-cookie";
import { Message } from 'element-ui';

axios.defaults.withCredentials = true;

//创建axios实例
const instance = axios.create({
  // `headers` 请求头的通用配置
  // headers: {
  //   // 'X-Requested-With': 'XMLHttpRequest'
  // },
  // baseURL: '',//远程的api地址
  timeout: 120000, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // withCredentials: false, // `withCredentials` 表示跨域请求时是否需要使用凭证
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // console.log(config, "请求拦截器");
    // 设置Content-Type、token等等
    if (!config.headers["Content-Type"]) {
      // config.headers["Content-Type"] = "application/json";
      // config.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
    }
    // config.headers["auth"] = localStorage.getItem("token");
    // 泽峰 对接星环
    config.headers["Authorization"] = Cookies.get("token") ? JSON.parse(Cookies.get("token")) : "";
    // console.log(Cookies.get("token"))
    // config.headers["Authorization"] = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiI0NWNiZjRkYzViNWY0MTA1ODBkMzQyMWIxMDJmNjIzYyIsInVzZXIiOiLmtYvor5UiLCJzdWIiOiLmtYvor5UifQ.KFxxnXc8FsKIRYlYZGq5qCRBMK6QyToKTkqwyhuzTecOByWY5KV0vm3KlTMEvZVanEocOeh3b19pFdlhQpbE4Q"

    return config;
  },
  error => {
    //统一错误处理...
    return Promise.reject(error);
  }
);

// instance.interceptors.request.use(
//   config => {
//       // 在发送请求之前添加请求头
//       // console.log(config);
//       const token = localStorage.getItem('token');
//       config.headers['Authorization'] = localStorage.getItem('token'); // 替换为你的 token 或其他请求头
//       // }
//       return config;
//   },
//   error => {
//       // 处理请求错误
//       return Promise.reject(error);
//   }
// );

// 响应拦截器
instance.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.data.ResultCode == 401) {//说明token过期或者鉴权失败
        alert('鉴权失败,您将强制退出登录');
        let cookieToken = Cookies.get("token");
        let user = Cookies.get("user");
        let localToken = localStorage.getItem("token");
        if(cookieToken && user && localToken) {
          //清空token
          // 跳转到登录页面
          Cookies.remove("user");
          Cookies.remove("token");
          Message.error('登录已过期，请重新登录！')
          localStorage.removeItem("token");
          //跳转到登录页
          // return router.push('/login');
          setTimeout(()=>{
            location.reload();
          }, 1000)
        }
      }
      return response.data;
      //return response; // 正常返回
    } else {
      return response;
    }
  },
  error => {
    let cookieToken = Cookies.get("token");
    let user = Cookies.get("user");
    let localToken = localStorage.getItem("token");
    if (cookieToken && user && localToken && error.response && error.response.status === 401) {
      // if (!Cookies.get("token")) return; // LZYFIX
      // 跳转到登录页面
      Cookies.remove("user");
      Cookies.remove("token");
      localStorage.removeItem("token");
      // router.push('/');
      Message.error('登录已过期，请重新登录！');
      setTimeout(()=>{
      router.go(0)
      // //   location.reload();
      }, 500)
    }
    return Promise.reject(error);
  }
);

export default instance
